package com.demo.juc.futuretask;


import java.util.concurrent.*;

/**
 * @Author: shubin_yao
 * @Date: 2022/09/25/9:58
 * @Description: 如何解决 FutrueTask 轮询和阻塞问题
 */
public class CompleteFutureTaskStage {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        try {
            //异步线程
            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                int result = ThreadLocalRandom.current().nextInt(10);
                //System.out.println(Thread.currentThread().isDaemon()); //没有线程池true
                //int i = 1/0;
                return result;
            }, threadPool).whenComplete((r, e) -> {
                if (e == null) {
                    System.out.println("加1得到：" + (r + 1));
                }
            }).whenComplete((r, e) -> {
                if (e == null) {
                    System.out.println("加2得到：" + (r + 2));
                }
            }).exceptionally(e -> {
                try {
                    System.out.println("异常处理：" + e.getCause() + "\t" + e.getMessage());
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                return 0;
            });
            System.out.println(completableFuture.get());
            System.out.println(Thread.currentThread().getName() + "执行。。。");
        } finally {
            threadPool.shutdown();
        }
    }
}
